<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row>
        <el-col :sm="18">
          <el-input
            v-model="listQuery.name"
            :placeholder="$t('table.name')"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >{{ $t('table.search') }}</el-button>
        </el-col>
        <el-col :sm="6">
          <div class="sg-table-top-right-box">
            <el-button
              v-waves
              :loading="exportLoading"
              class="filter-item"
              type="primary"
              icon="el-icon-download"
              @click="handleExport"
            >{{ $t('table.export') }}</el-button>
            <el-button
              class="filter-item"
              style="margin-left: 10px;"
              type="primary"
              icon="el-icon-edit"
              @click="handleCreate"
            >{{ $t('table.add') }}</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      stripe
      border
      fit
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column :label="$t('table.name')" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button-group>
            <el-button size="mini" type="primary" @click="handleUpdate(row)">{{ $t('table.edit') }}</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(row, 'deleted')"
            >{{ $t('table.delete') }}</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="dialogTitleMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="model" label-position="left" label-width="70px">
        <el-row>
          <el-col :span="18" :offset="3">
            <el-form-item label="名称" prop="name">
              <el-input v-model="model.name"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="3">
            <el-form-item label="上传" prop="uploadImages">
              <UploadImage v-model="model.banners" :multiple="true"></UploadImage>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="3">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="model.sort"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button
          type="primary"
          @click="dialogStatus==='create'?createData():updateData()"
        >{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { showStatusFilter } from "@/filters/index";
import {
  fetchList,
  createModel,
  updateModel,
  deleteModel
} from "@/api/admin-photo-categories";
import waves from "@/directive/waves"; // waves directive
import { parseTime, formatDate } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import UploadImage from "@/components/Upload/UploadImage";
import { QiniuBaseUrl } from "@/settings"

export default {
  name: "AdminPhotoCategory",
  components: { Pagination, UploadImage },
  directives: { waves },
  filters: {},
  data() {
    return {
      tableKey: 0,
      modelName: "图片分类",
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        sort: "+id"
      },
      showOptions: [{ key: "1", value: "显示" }, { key: "2", value: "不显示" }],
      initModel: {
        id: undefined,
        name: "",
        banners: "",
        bannerList: [],
        bannerFileList: [],
        sort: 0
      },
      model: {},
      dialogFormVisible: false,
      dialogStatus: "",
      rules: {
        name: [{ required: true, message: "名称必填", trigger: "blur" }]
      },
      exportLoading: false,
      exportHeader: ["id", "name", "sort"]
    };
  },
  computed: {
    dialogTitleMap: function() {
      return {
        update: "编辑" + this.modelName,
        create: "创建" + this.modelName
      };
    }
  },
  created() {
    this.resetModel();
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then(response => {
        this.listLoading = false;
        if (response.data.code === 20000) {
          let data = response.data;
          this.list = data.data.data;
          this.total = data.data.total;
        }
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetModel() {
      this.model = Object.assign({}, this.initModel);
    },
    handleCreate() {
      this.resetModel();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          createModel({
            name: this.model.name,
            banners: this.model.bannerList.join(','),
            sort: this.model.sort
          }).then(response => {
            this.dialogFormVisible = false;
            if (response.data.code === 20000) {
              this.$notify({
                title: "成功",
                message: "创建成功",
                type: "success",
                duration: 2000
              });
              this.getList();
            }
          });
        }
      });
    },
    handleUpdate(row) {
      this.model = Object.assign({}, row);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const modelData = Object.assign({}, this.model);
          modelData.bannerList = modelData.split(',')
          updateModel(modelData).then(response => {
            this.dialogFormVisible = false;
            if (response.data.code === 20000) {
              for (const v of this.list) {
                if (v.id === this.model.id) {
                  const index = this.list.indexOf(v);
                  this.list.splice(index, 1, this.model);
                  break;
                }
              }
              this.$notify({
                title: "成功",
                message: "更新成功",
                type: "success",
                duration: 2000
              });
            }
          });
        }
      });
    },
    handleDelete(row) {
      this.$confirm("删除后将不可恢复", "确定要删除吗？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteModel({ id: row.id }).then(response => {
          this.dialogFormVisible = false;
          if (response.data.code === 20000) {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
            const index = this.list.indexOf(row);
            this.list.splice(index, 1);
          }
        });
      });
    },
    handleExport() {
      this.exportLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = this.exportHeader;
        const filterVal = this.exportHeader;
        const data = this.formatJson(filterVal, this.list);
        const filename =
          this.modelName + "列表" + formatDate(new Date(), "yyyy-MM-dd");
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: filename
        });
        this.exportLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "show") {
            return showStatusFilter(v[j]);
          } else {
            return v[j];
          }
        })
      );
    }
  }
};
</script>
